package com.example.exchangerate;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class MainActivity extends AppCompatActivity {
    public
    int standard_pos = 0;
    String current_from = "人民币(CNY)"; //待转换货币
    String current_to = "人民币(CNY)";   //转换货币
    List<Current> currents;     //货币-人民币汇率列表
    List<Price> prices = new ArrayList<Price>(){{   //货币价值列表
        add(new Price("人民币(CNY)", 1.0));
        add(new Price("美元(USD)", 1.0)); 
        add(new Price("欧元(EUR)", 1.0));
        add(new Price("日元(JPY)", 1.0));
        add(new Price("港币(HKD)", 1.0));
        add(new Price("英镑(GBP)", 1.0));
        add(new Price("澳元(AUD)", 1.0));
        add(new Price("新西兰元(NZD)", 1.0));
        add(new Price("新加坡元(SGD)", 1.0));
        add(new Price("瑞士法郎(CHF)", 1.0));
        add(new Price("加元(CAD)", 1.0));
        add(new Price("林吉特(MYR)", 1.0));
        add(new Price("俄罗斯卢布(RUB)", 1.0));
        add(new Price("南非兰特(ZAR)", 1.0));
        add(new Price("韩元(KRW)", 1.0));
        add(new Price("阿联酋迪拉姆(AED)", 1.0));
        add(new Price("沙特里亚尔(SAR)", 1.0));
        add(new Price("匈牙利福林(HUF)", 1.0));
        add(new Price("波兰兹罗提(PLN)", 1.0));
        add(new Price("丹麦克朗(DKK)", 1.0));
        add(new Price("瑞典克朗(SEK)", 1.0));
        add(new Price("挪威克朗(NOK)", 1.0));
        add(new Price("土耳其里拉(TRY)", 1.0));
        add(new Price("墨西哥比索(MXN)", 1.0));
        add(new Price("泰铢(THB)", 1.0));
    }};
    CurrentAdapter currentAdapter = null;
    ListView listView = null;
    private Lock lock = new ReentrantLock();    //互斥锁，用于保护prices

    //更新货币价值
    void FlushPrice() throws InterruptedException {
        prices.get(standard_pos).setVal(1.00000000);
        if(standard_pos != 0)
            prices.get(0).setVal(1.0 / currents.get(standard_pos - 1).getPrice());
        for (int i = 1; i < 25; i++) {
            double RMB_rate = currents.get(i - 1).getPrice();
            if(standard_pos != 0) {
                RMB_rate = currents.get(i - 1).getPrice() * prices.get(0).getVal();
            }
            if (i == standard_pos) continue;
            prices.get(i).setVal(RMB_rate);
        }
    }

    //网络请求线程，发送汇率API的请求
    class HttpThread extends Thread{
        @Override
        public void run() {
            while(true){
                try {
                    String app_id = "pvwkqgheebrjwphp";
                    String app_secret = "eThudzFkdkpuYjZzb0ZYY1NrSnlxQT09";
                    URL url = new URL("https://www.mxnzp.com/api/exchange_rate/list?app_id="
                            + app_id + "&app_secret=" + app_secret);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    int code = connection.getResponseCode();//获取返回码
                    InputStream stream;
                    if (code == 200)
                        stream = connection.getInputStream();
                    else
                        stream = connection.getErrorStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
                    String line = reader.readLine();
                    Gson gson = new Gson();
                    String data = line.substring(line.indexOf("["), line.length() - 1);
                    currents = gson.fromJson(data, new TypeToken<List<Current>>(){}.getType());
                    currents.get(2).setPrice(currents.get(2).getPrice() / 100.0);
                    for(int i = 9; i < currents.size(); i++)
                        currents.get(i).setPrice(1.0 / currents.get(i).getPrice());
                    FlushPrice();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                double wave = Math.random() / 1000.0 + 1.0;
                                lock.lock();
                                if(Math.random() > 0.5)
                                    for(int i = 0; i < 25; i++)
                                        if(i != standard_pos)
                                            prices.get(i).setVal(prices.get(i).getVal() * wave);
                                currentAdapter.notifyDataSetChanged();
                            } finally {
                                lock.unlock();
                            }
                            currentAdapter.notifyDataSetChanged();
                        }
                    });
//                    Log.d("cs_current", currents.get(0).name + " " + currents.get(0).price);
                    connection.disconnect();
                    Thread.sleep(2000);
                } catch (IOException | InterruptedException e) { e.printStackTrace(); }
            }
        }
    }

    //EditText输入完成后，点击外部自动退出软键盘
    @Override
    public boolean dispatchTouchEvent(MotionEvent mev) {
        View view = getCurrentFocus();
        if (view != null
                && (mev.getAction() == MotionEvent.ACTION_UP || mev.getAction() == MotionEvent.ACTION_MOVE)
                && view instanceof EditText
                && !view.getClass().getName().startsWith("android.webkit.")) {
            int[] pos = new int[2];
            view.getLocationOnScreen(pos);
            double posx = mev.getRawX() + view.getLeft() - pos[0];
            double posy = mev.getRawY() + view.getTop() - pos[1];
            if (posx < view.getLeft() || posx > view.getRight()
                    || posy < view.getTop() || posy > view.getBottom()) {
                hideKeyboard(this);
            }
        }
        return super.dispatchTouchEvent(mev);
    }
    //隐藏软键盘
    private void hideKeyboard(Activity activity) {
        findViewById(android.R.id.content).clearFocus();
        if (activity != null && activity.getWindow() != null) {
            activity.getWindow().getDecorView();
            InputMethodManager inputMethodManager
                    = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            if (inputMethodManager != null) {
                inputMethodManager.hideSoftInputFromWindow(activity.getWindow().getDecorView().getWindowToken(), 0);
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //汇率提取部分
        HttpThread httpThread = new HttpThread();
        httpThread.start();
        //隐藏自带标题
        ActionBar actionBar = getSupportActionBar();
        if(actionBar != null) actionBar.hide();
        //汇率转换部分
        EditText editText_from = (EditText) findViewById(R.id.input_from);
        EditText editText_to = (EditText) findViewById(R.id.input_to);
        Spinner spinnerFrom = (Spinner) findViewById(R.id.spinner_from);
        Spinner spinnerTo = (Spinner) findViewById(R.id.spinner_to);
        ArrayList<String> optionFrom = new ArrayList<String>();
        Collections.addAll(optionFrom, "人民币(CNY)", "美元(USD)", "欧元(EUR)", "日元(JPY)",
                "港币(HKD)", "英镑(GBP)", "澳元(AUD)", "新西兰元(NZD)", "新加坡元(SGD)", "瑞士法郎(CHF)",
                "加元(CAD)", "林吉特(MYR)", "俄罗斯卢布(RUB)", "南非兰特(ZAR)", "韩元(KRW)",
                "阿联酋迪拉姆(AED)", "沙特里亚尔(SAR)", "匈牙利福林(HUF)", "波兰兹罗提(PLN)", "丹麦克朗(DKK)",
                "瑞典克朗(SEK)", "挪威克朗(NOK)", "土耳其里拉(TRY)", "墨西哥比索(MXN)", "泰铢(THB)");
        ArrayList<String> optionTo = new ArrayList<String>(optionFrom);
        final ArrayAdapter<String> adapterFrom = new ArrayAdapter<String>
                (MainActivity.this, R.layout.spinner_text_from, optionFrom);
        final ArrayAdapter<String> adapterTo = new ArrayAdapter<String>
                (MainActivity.this, R.layout.spinner_text_to, optionTo);
        spinnerFrom.setAdapter(adapterFrom);
        spinnerTo.setAdapter(adapterTo);
        spinnerFrom.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            //选取时候的操作
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                current_from = spinnerFrom.getSelectedItem().toString();
                current_to = spinnerTo.getSelectedItem().toString();
                String valf = editText_from.getText().toString();
                try {
                    int pos_from = spinnerFrom.getSelectedItemPosition();
                    int pos_to = spinnerTo.getSelectedItemPosition();
                    double val_from = Double.parseDouble(valf);
                    double val_to = val_from / prices.get(pos_to).getVal() * prices.get(pos_from).getVal();
                    editText_to.setText(val_to + "");
                }catch (Exception e){
                    editText_to.setText("");
                }
            }
            //没被选取时的操作
            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });
        spinnerTo.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            //选取时候的操作
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                spinnerFrom.getOnItemSelectedListener().onItemSelected(parent, view, position, id);
            }
            //没被选取时的操作
            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });
        editText_from.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(!editText_from.hasFocus()) {
                    current_from = spinnerFrom.getSelectedItem().toString();
                    current_to = spinnerTo.getSelectedItem().toString();
                    String valf = editText_from.getText().toString();
                    try {
                        int pos_from = spinnerFrom.getSelectedItemPosition();
                        int pos_to = spinnerTo.getSelectedItemPosition();
                        double val_from = Double.parseDouble(valf);
                        double val_to = val_from / prices.get(pos_to).getVal() * prices.get(pos_from).getVal();
                        editText_to.setText(val_to + "");
                    }catch (Exception e){
                        editText_to.setText("");
                    }
                }
            }
        });
        //汇率展示部分
        currentAdapter = new CurrentAdapter(MainActivity.this, R.layout.current_price, prices);
        listView = findViewById(R.id.list_view);
        listView.setAdapter(currentAdapter);
        //汇率列表切换部分
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                standard_pos = position;
                try {
                    lock.lock();
                    FlushPrice();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    lock.unlock();
                }
                currentAdapter.setSelectedPos(position);
                currentAdapter.notifyDataSetInvalidated();
                findViewById(R.id.input_from).clearFocus();
                Price price = prices.get(position);
                Toast.makeText(MainActivity.this
                        , price.getName() + "已设为标准对比货币", Toast.LENGTH_SHORT).show();
            }
        });
    }
}